package me.sdevil507.activemq.sync;

import me.sdevil507.activemq.QueueName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * 同步消息消费者
 * <p>
 * 接收到消息同时回复一条消息
 *
 * @author sdevil507
 */
@Component
public class SyncCustomer {

    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     * 同步模式下的消息消费方法
     * <p>
     * concurrency属性配置多个消费者并发消费消息
     *
     * @param message 消息
     * @return 返回回复内容
     */
    @JmsListener(destination = QueueName.SYNC, concurrency = "5-20")
    public String receiveSyncMessage(Message message) {
        try {
            // 判断消息是否包含回执
            if (message.getJMSReplyTo() != null && message instanceof TextMessage) {
                String text = ((TextMessage) message).getText();
                System.out.println("线程:" + Thread.currentThread().getName() + "[id:" + text + "]");
                // 自定义逻辑,包含下列字符串时,处理时长较久
                String tempID = "3";
                if (text.contains(tempID)) {
                    Thread.sleep(10000);
                }
                // 通过回执,给生产者回复消息
                jmsTemplate.send(message.getJMSReplyTo(), new MessageCreator() {
                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        Message result = session.createTextMessage("处理了ID为" + text + "的消息,并给予返回!");
                        // 设置相关ID
                        result.setJMSCorrelationID(message.getJMSCorrelationID());
                        return result;
                    }
                });
            }
        } catch (JMSException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
